import { getVehicleList, getVehicleDetail, getVehicleBrands } from '@/api/vehicle'

const state = {
  vehicleList: [],
  vehicleDetail: null,
  brands: [],
  total: 0,
  loading: false
}

const mutations = {
  SET_VEHICLE_LIST: (state, { list, total }) => {
    state.vehicleList = list
    state.total = total
  },
  SET_VEHICLE_DETAIL: (state, detail) => {
    state.vehicleDetail = detail
  },
  SET_BRANDS: (state, brands) => {
    state.brands = brands
  },
  SET_LOADING: (state, loading) => {
    state.loading = loading
  }
}

const actions = {
  // 获取车辆列表
  getVehicleList({ commit }, query) {
    commit('SET_LOADING', true)
    return new Promise((resolve, reject) => {
      getVehicleList(query)
        .then(response => {
          const { data } = response
          commit('SET_VEHICLE_LIST', {
            list: data.records || [],
            total: data.total || 0
          })
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
        .finally(() => {
          commit('SET_LOADING', false)
        })
    })
  },

  // 获取车辆详情
  getVehicleDetail({ commit }, id) {
    commit('SET_LOADING', true)
    return new Promise((resolve, reject) => {
      getVehicleDetail(id)
        .then(response => {
          const { data } = response
          commit('SET_VEHICLE_DETAIL', data)
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
        .finally(() => {
          commit('SET_LOADING', false)
        })
    })
  },

  // 获取车辆品牌列表
  getVehicleBrands({ commit }) {
    return new Promise((resolve, reject) => {
      getVehicleBrands()
        .then(response => {
          const { data } = response
          commit('SET_BRANDS', data || [])
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
} 